package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.View.GONE;


public class AffirmEditActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int MSG_GetProcOver = 1001;
    public static final int MSG_ERRMSG = 1002;
    public static final int MSG_SaveTransOver = 1003;
    public static final int MSG_GETDEPART=1005;
    //全局变量
    String SaveFilePath="",SaveDBFolder="/DB";
    public static final String DB_Name ="bdmes.db";
    SQLiteDatabase mainDB;

    //全局提示;
    Toast curToast;
    private ProgressDialog waitDialog = null;
    //布局元素;
    ListView procList,sonList,reasonList;
    TextView view_rtpStyleNoText,view_styleNoText,view_styleSortText;
    //全局变量
    String curLoginUserNo,curLoginUser,serviceUrl="",curDepartNo="",curDepart="",curWorkNo="",
            curKeyID="",curOrderNo ="",  curRptStyleNo ="",curStyleNo ="",curStyleSort="",curFactory="";//操作员所属部门等信息;
    String CPUID="",curServiceUrl="",curServiceDir="",WorkSection="SEW",AllowAffirm="",AllowUnAffirm="";
    boolean dataEditSign=false;
    Spinner reasonSpinner;
    int maxWorkNo=0;
    EditText edt_WorkNo,edt_WorkName;
    //当前选中的内容;
    private JSONArray procJSONArray,resultJson,splitJSON,reasonJSON;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //启动Activity
        setContentView(R.layout.activity_affirmedit);
        hideBottomUIMenu();

        //创建对话框，
        waitDialog=new ProgressDialog(this);
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNo");
        curDepart=paramBundle.getString("CurDepart");
        curFactory=paramBundle.getString("CurFactory");
        curOrderNo=paramBundle.getString("CurOrderNo");
        curRptStyleNo=paramBundle.getString("CurRptStyleNo");
        curStyleNo=paramBundle.getString("CurStyleNo");
        curStyleSort=paramBundle.getString("CurStyleSort");
        curKeyID=paramBundle.getString("CurKeyID");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        WorkSection=paramBundle.getString("WorkSection","SEW");
        AllowAffirm=paramBundle.getString("AllowAffirm","N");
        AllowUnAffirm=paramBundle.getString("AllowUnAffirm","N");
        CPUID=paramBundle.getString("CPUID");
        System.out.println(paramBundle);
        //初始化按键，并将页面加载到fragment列表中;
        InitView();
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        findViewById(R.id.view_rtpStyleNoText).postDelayed(new Runnable() {
            public void run() {
                refreshProcList(curDepartNo,curKeyID,curOrderNo,curRptStyleNo,curStyleNo,curStyleSort,curLoginUserNo);
            }
        }, 500);
        mainDB.execSQL("Delete from ReasonDe");
        try {
            JSONArray reasonJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }



    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }


    // /判断外部存储是否可读写
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    private void InitView() {
        reasonSpinner=findViewById(R.id.reasonSpinner);
        sonList=findViewById(R.id.sonList);
        reasonList=findViewById(R.id.reasonList);
        //表格
        procList =(ListView)findViewById(R.id.procList);
        procList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                try {
                    String prWorkNo="";
                    prWorkNo=procJSONArray.optJSONObject(position).getString("WorkNo");
                    if (curWorkNo!=null&&curWorkNo.length()>0&&prWorkNo!=curWorkNo&&splitJSON!=null&&splitJSON.length()>0){
                        final String finalPrWorkNo = prWorkNo;
                        AlertDialog alertDialog = new AlertDialog.Builder(procList.getContext())
                                .setTitle("系统提示").setMessage(curWorkNo+"工序有拆分工序未保存,确定要切换吗？")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        mainDB.execSQL("Delete from ReasonDe where PrWorkNo=?",new String[]{curWorkNo});
                                        GetDetail(finalPrWorkNo);
                                        return;
                                    }
                                }).create(); // 创建对话框
                        alertDialog.show(); // 显示对话框
                    }  else GetDetail(prWorkNo);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("ViewFragment..............................3");
        findViewById(R.id.btn_tmpSave).setOnClickListener(this);
        findViewById(R.id.btn_addSonProc).setOnClickListener(this);
        findViewById(R.id.btn_saveData).setOnClickListener(this);
        findViewById(R.id.btn_returnData).setOnClickListener(this);

        //界面显示
        view_rtpStyleNoText=(TextView)findViewById(R.id.view_rtpStyleNoText);
        view_styleNoText=(TextView)findViewById(R.id.view_styleNoText);
        view_styleSortText=(TextView)findViewById(R.id.view_styleSortText);

        System.out.println("ViewFragment..............................4");

        findViewById(R.id.btn_Close).setOnClickListener(this);
        System.out.println("ViewFragment..............................5");
        //初始提醒;
        curToast = Toast.makeText(this, getString(R.string.SystemHint), Toast.LENGTH_LONG);
        view_rtpStyleNoText.setText(curRptStyleNo);
        view_styleNoText.setText(curStyleNo);
        view_styleSortText.setText(curStyleSort);
    }


    //获取明细
    private void GetDetail(String paramPrWorkNo){
        curWorkNo=paramPrWorkNo;
        try{
            splitJSON=new JSONArray("[]");
            Cursor cursor=mainDB.rawQuery("Select PrWorkNo,WorkNo,WorkName from ReasonDe where PrWorkNo=?",new String[]{paramPrWorkNo});
            while (cursor.moveToNext()){
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("PrWorkNo",cursor.getString(0));
                jsonObject.put("WorkNo",cursor.getString(1));
                jsonObject.put("WorkName",cursor.getString(2));
                splitJSON.put(jsonObject);
            }
            cursor.close();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //更新到数据库
        if (sonList.getAdapter()!=null) ((BaseAdapter) sonList.getAdapter()).notifyDataSetChanged();
        else{
            DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
            sonList.setAdapter(detailListAdapter);
        }
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    private void showPopSonProc(final int paramPostion, String paramTitle, final String paramPrWorkNo,final String paramWorkNo,final String paramWorkName){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View pull_input=inflater.inflate(R.layout.activity_affirmedit_popson, null);
        edt_WorkNo=pull_input.findViewById(R.id.edt_WorkNo);
        edt_WorkNo.setEnabled(false);
        edt_WorkNo.setOnClickListener(this);
        edt_WorkName=pull_input.findViewById(R.id.edt_WorkName);
        edt_WorkName.setOnClickListener(this);
        edt_WorkNo.setText(paramWorkNo);
        edt_WorkName.setText(paramWorkName);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(pull_input).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (edt_WorkNo.getText().toString().length() == 0 ||
                                edt_WorkName.getText().toString().length() == 0) {
                            curToast.setText("请将数据输入完整!");
                            curToast.show();
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        } else {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                                try {
                                    if (paramPostion >= 0) {
                                        splitJSON.optJSONObject(paramPostion).put("WorkName", edt_WorkName.getText().toString());
                                        //更新到数据库
                                        ((BaseAdapter) sonList.getAdapter()).notifyDataSetChanged();
                                        mainDB.execSQL("Update ReasonDe Set WorkName=? where WorkNo=?",
                                                new Object[]{edt_WorkName.getText().toString(), edt_WorkNo.getText().toString()});
                                    } else{
                                        JSONObject jsonObject=new JSONObject();
                                        jsonObject.put("PrWorkNo",paramPrWorkNo);
                                        jsonObject.put("WorkNo", edt_WorkNo.getText().toString());
                                        jsonObject.put("WorkName",edt_WorkName.getText().toString());
                                        splitJSON.put(jsonObject);
                                        mainDB.execSQL("insert into ReasonDe(PrWorkNo,WorkNo,WorkName) values(?,?,?)",
                                                new Object[]{paramPrWorkNo,edt_WorkNo.getText().toString(),
                                                        edt_WorkName.getText().toString()});
                                        ((BaseAdapter) sonList.getAdapter()).notifyDataSetChanged();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            } catch (IllegalAccessException | NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                        }
                        //保存;
                        hideIM(pull_input);
                    }
                }
        ).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                hideIM(pull_input);
                Field field = null;
                try {
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(paramTitle);
        builder.show();
    }


    //自定义适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return splitJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return splitJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_affirmedit_splititem, null, false);
            int pullVatListWidth=parent.getWidth();
            int color = getResources().getColor(R.color.text_black);
            int backcolor = getResources().getColor(R.color.content);
            ViewHolder holder = new ViewHolder();
            holder.btn_delItem = view.findViewById(R.id.btn_delItem);
            holder.btn_delItem.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    try {
                        String workNo=splitJSON.getJSONObject(position).getString("WorkNo");
                        splitJSON.remove(position);
                        ((BaseAdapter)sonList.getAdapter()).notifyDataSetChanged();
                        mainDB.execSQL("Delete from ReasonDe where WorkNo=?",new Object[]{workNo});
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            holder.btn_editItem = view.findViewById(R.id.btn_editItem);
            holder.btn_editItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        String prWorkNo = splitJSON.optJSONObject(position).getString("PrWorkNo");
                        String workNo = splitJSON.optJSONObject(position).getString("WorkNo");
                        String workName= splitJSON.optJSONObject(position).getString("WorkName");
                        showPopSonProc(position,"修改工序", prWorkNo,workNo,workName);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            view.setTag(holder);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                if (splitJSON.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = splitJSON.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if (splitJSON.optJSONObject(position).has("WorkNo") == true) {
                    ((TextView)view.findViewById(R.id.Item_WorkNo)).setText(splitJSON.optJSONObject(position).getString("WorkNo"));
                    ((TextView)view.findViewById(R.id.Item_WorkNo)).setTextColor(color);
                }
                if (splitJSON.optJSONObject(position).has("WorkName") == true) {
                    ((TextView)view.findViewById(R.id.Item_WorkName)).setText(splitJSON.optJSONObject(position).getString("WorkName"));
                    ((TextView)view.findViewById(R.id.Item_WorkName)).setTextColor(color);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }

        //提取出来方便点
        public final class ViewHolder {
            public Button btn_delItem;
            public Button btn_editItem;
        }
    }

    private boolean CheckRepeat(String paramWorkNo){
        boolean result=false;
        if (reasonJSON!=null&&reasonJSON.length()>0){
            try {
                for(int i=0;i<reasonJSON.length();i++){
                    if (paramWorkNo.equals(reasonJSON.optJSONObject(i).getString("WorkNo")))
                        return true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_addSonProc:
                int tmpWorkNo=0;
                System.out.println("procList.getCheckedItemPosition():"+procList.getCheckedItemPosition());
                if (procList.getCheckedItemPosition()>-1) {
                    try {
                        String workNo = procJSONArray.optJSONObject(procList.getCheckedItemPosition()).getString("WorkNo");
                        String workName= procJSONArray.optJSONObject(procList.getCheckedItemPosition()).getString("WorkName");
                        Cursor cur=mainDB.rawQuery("Select Max(CAST(WorkNo as int)) WorkNo from ReasonDe",null);
                        if (cur.getCount()>0) {
                            cur.moveToFirst();
                            if (cur.getInt(0)>0)
                                tmpWorkNo=cur.getInt(0)+1;
                            else tmpWorkNo=maxWorkNo+1;
                        }
                        else tmpWorkNo=maxWorkNo+1;
                        cur.close();
                        showPopSonProc(-1,"新增工序",workNo,String.valueOf(tmpWorkNo),workName);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else {
                    curToast.setText("请先选择工序");
                    curToast.show();
                }
                break;
            case R.id.btn_tmpSave:
                if (procList.getCheckedItemPosition()>-1) {
                    try {
                        String workNo = procJSONArray.optJSONObject(procList.getCheckedItemPosition()).getString("WorkNo");
                        String workName= procJSONArray.optJSONObject(procList.getCheckedItemPosition()).getString("WorkName");
                        if (CheckRepeat(workNo)){
                            curToast.setText("不能重复添加！");
                            curToast.show();
                            return;
                        }
                        TextView reasonTxt = (TextView) reasonSpinner.getSelectedView();
                        String reason=reasonTxt.getText().toString();
                        System.out.println("A");
                        String SplitInfo="";
                        if (reason.equals("A:工序需拆分")==true){
                            if (splitJSON!=null&&splitJSON.length()>0){
                                for(int i=0;i<splitJSON.length();i++){
                                    String sonWorkNo=splitJSON.optJSONObject(i).getString("WorkNo");
                                    String sonWorkName=splitJSON.optJSONObject(i).getString("WorkName");
                                    if (SplitInfo.length()==0) SplitInfo=sonWorkNo+":"+sonWorkName; else SplitInfo=SplitInfo+";"+sonWorkNo+":"+sonWorkName;
                                }
                            } else {
                                curToast.setText("请拆分工序后保存!");
                                curToast.show();
                                return;
                            }
                        }
                        System.out.println("B");
                        if (reasonJSON==null) reasonJSON=new JSONArray("[]");
                        //整理原因并显示;
                        JSONObject jsonObject=new JSONObject();
                        jsonObject.put("WorkNo",workNo);
                        jsonObject.put("WorkName",workName);
                        jsonObject.put("Reason",reason);
                        jsonObject.put("SplitInfo",SplitInfo);
                        reasonJSON.put(jsonObject);
                        System.out.println(reasonJSON);
                        ReasonListAdapter reasonListAdapter=new ReasonListAdapter(reasonList.getContext());
                        reasonList.setAdapter(reasonListAdapter);
                        curWorkNo="";
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    curToast.setText("请先选择工序");
                    curToast.show();
                }

                break;
            case R.id.btn_returnData:
                saveData(curDepart,curKeyID,curOrderNo,curRptStyleNo,curStyleNo,curStyleSort,"Return");
                break;
            case R.id.btn_saveData:
                saveData(curDepart,curKeyID,curOrderNo,curRptStyleNo,curStyleNo,curStyleSort,"Affirm");
                break;

            case R.id.btn_Close:
                AlertDialog alertDialog2 = new AlertDialog.Builder(v.getContext())
                        .setTitle("系统提示").setMessage("你确定要关闭当前窗口？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //返回
                                Intent intent = new Intent();
                                intent.putExtra("CurKeyID",curKeyID);
                                intent.putExtra("AllowAffirm",AllowAffirm);
                                setResult(1001,intent);
                                finish();
                            }
                        }).setNeutralButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog2.show(); // 显示对话框
                break;
            default:
                break;
        }
    }

    //提交所选择的工序至服务器,然后刷新工序列表;
    private void saveData(final String paramDepart,  final String paramKeyID, final String paramOrderNo, final String paramRptStyleNo, final String paramStyleNo, final String paramStyleSort,final String paramTransMethod){
        if (paramTransMethod.equals("Return") &&(reasonJSON == null || reasonJSON.length()==0)) {
            curToast.setText("退回需要暂存退回原因！");
            curToast.show();
            return;
        }
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String AffirmEditID = java.util.UUID.randomUUID().toString();
                //将数据读到JSONArray;
                try {
                    System.out.println("saveData:"+1);

                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Insert into AffirmEditDe(AffirmEditDeID,AffirmEditID,WorkNo,WorkName,Reason,SplitInfo) values(newid(),?,?,?,?,?)");
                    //增加明细表
                    if (reasonJSON!=null)
                    for (int i = 0; i < reasonJSON.length(); i++) {
                        if (reasonJSON.getJSONObject(i).has("WorkNo") == true) {
                            if (reasonJSON.getJSONObject(i).getString("WorkNo").length() > 0) {
                                pstmt.setString(1, AffirmEditID);
                                pstmt.setString(2, reasonJSON.getJSONObject(i).getString("WorkNo"));
                                pstmt.setString(3, reasonJSON.getJSONObject(i).getString("WorkName"));
                                pstmt.setString(4, reasonJSON.getJSONObject(i).getString("Reason"));
                                pstmt.setString(5, reasonJSON.getJSONObject(i).getString("SplitInfo"));
                                System.out.println(i+"->"+"WorkNo:"+ procJSONArray.getJSONObject(i).getString("WorkNo")+" WorkName:"+procJSONArray.getJSONObject(i).getString("WorkName"));
                                pstmt.executeUpdate();
                            }
                        }
                    }
                    pstmt.close();

                    //增加主表;
                    System.out.println("saveData:"+2+"-start");
                    pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Insert into AffirmEdit(AffirmEditID,Depart,KeyID,OrderNo,RptStyleNo,StyleNO,StyleSort,UserNo,UserName,CreateTime) values(?,?,?,?,?,?,?,?,?,getdate())");
                    pstmt.setString(1, AffirmEditID);
                    pstmt.setString(2, paramDepart);
                    pstmt.setString(3, paramKeyID);
                    pstmt.setString(4, paramOrderNo);
                    pstmt.setString(5, paramRptStyleNo);
                    pstmt.setString(6, paramStyleNo);
                    pstmt.setString(7, paramStyleSort);
                    pstmt.setString(8, curLoginUserNo);
                    pstmt.setString(9, curLoginUser);
                    pstmt.executeUpdate();
                    pstmt.close();
                    System.out.println("saveData:"+2+"-end");
                    System.out.println();
                    //调用存储过程;
                    SqlComm = " Exec ScenePAD_AffirmEditSaveTrans @OperType='SaveTrans',@FormType='AffirmEdit',@TransMethod='"+paramTransMethod+"',@AffirmEditID='" + AffirmEditID + "'";
                    System.out.println("saveData:"+3+"->SqlComm:"+SqlComm);
                    ReadSQLData(SqlComm);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        };
        new Thread(run).start();
    }


    //订单表格适配器;
    public final class ReasonListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ReasonListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return reasonJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return reasonJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.activity_affirmedit_reasonitem, null, false);
            try {
                ViewHolder holder = new ViewHolder();
                holder.btn_delItem = convertView.findViewById(R.id.btn_delItem);
                holder.btn_delItem.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        try {
                            String workNo=reasonJSON.getJSONObject(position).getString("WorkNo");
                            reasonJSON.remove(position);
                            ((BaseAdapter)reasonList.getAdapter()).notifyDataSetChanged();
                        }
                        catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                TextView tv =convertView.findViewById(R.id.txt_WorkNo);// 显示文字
                if (reasonJSON.optJSONObject(position).has("WorkNo")) tv.setText(reasonJSON.optJSONObject(position).get("WorkNo").toString());
                tv =  convertView.findViewById(R.id.txt_WorkName);// 显示文字
                if (reasonJSON.optJSONObject(position).has("WorkName")) tv.setText(reasonJSON.optJSONObject(position).get("WorkName").toString());
                tv =  convertView.findViewById(R.id.txt_Reason);// 显示文字
                if (reasonJSON.optJSONObject(position).has("Reason")) tv.setText(reasonJSON.optJSONObject(position).get("Reason").toString());
                tv =  convertView.findViewById(R.id.txt_SplitInfo);// 显示文字
                if (reasonJSON.optJSONObject(position).has("SplitInfo")) {
                    String  SplitInfo=reasonJSON.optJSONObject(position).get("SplitInfo").toString();
                    if (SplitInfo.length()>0)  tv.setText(SplitInfo);
                    else{
                        convertView.findViewById(R.id.txt_SplitInfoTitle).setVisibility(GONE);
                        convertView.findViewById(R.id.txt_SplitInfo).setVisibility(GONE);
                    }

                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            return convertView;
        }


        //提取出来方便点
        public final class ViewHolder {
            public Button btn_delItem;
        }
    }
    //刷新工序列表;
    private void refreshProcList(final String paramDepart,  final String paramKeyID, final String paramOrderNo, final String paramRptStyleNo, final String paramStyleNo, final String paramStyleSort,final String paramUserNo)
    {
        waitDialog.setMessage(getString(R.string.WaitingFromNetGetData));
        //执行SQL过程
        String SqlComm = "Exec ScenePAD_AffirmGetProc  @OperType='GetProc',@DepartmentNo='" + paramDepart+ "',@KeyID='" + paramKeyID  + "',@OrderNo='" + paramOrderNo
                + "',@RptStyleNo='" + paramRptStyleNo+ "',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort + "',@UserNo='" + paramUserNo + "',@WorkSection='" + WorkSection + "'";
        //调用WebService过程并处理界面更新;
        Log.d("msg", "serviceUrl------------------" + serviceUrl);
        ReadSQLData(SqlComm);
    }




    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println(SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    String OperType="";
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)){

                        if (jsonArray.optJSONObject(0).has("OperType")==true)  OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true)  OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");

                        //返回的为状态数据;
                        if (OperType.equals("GetProc"))
                        {
                            //关闭ProgressDialog
                            waitDialog.hide();
                            Log.d("msg","GetDaliyCount--------------------2");
                            procJSONArray =jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_GetProcOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OperType.equals("SaveTrans"))
                        {
                            //关闭ProgressDialog
                            waitDialog.hide();
                            Log.d("msg","MSG_SaveTransOver--------------------2");
                            resultJson =jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_SaveTransOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                        if (jsonArray.optJSONObject(0).has("ErrInfo")==true)
                        {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("ErrInfo"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }

                    } else{
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG","未返回数据");
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG",e.getMessage());
                    msg.setData(bundle);
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                }
            }

        };
        new Thread(run).start();

    }


    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                //消息处理;
                System.out.println("收到的消息是："+msg.what);
                //关闭ProgressDialog
                if (waitDialog.isShowing()) waitDialog.hide();
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_GetProcOver:
                        dataEditSign=false;
                        String tmpWorkNo="";
                        if (procJSONArray!=null&&procJSONArray.length()>0){
                            if (procJSONArray.optJSONObject(0).has("WorkNo")) {
                                try {
                                    for (int i = 0; i < procJSONArray.length(); i++) {
                                        tmpWorkNo = procJSONArray.optJSONObject(i).getString("WorkNo");
                                        if (isNumer(tmpWorkNo))   maxWorkNo=Integer.parseInt(tmpWorkNo);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        ProcListAdapter procListAdapter=new ProcListAdapter(procList.getContext());
                        procList.setAdapter(procListAdapter);
                        break;
                    case MSG_SaveTransOver:
                        if (resultJson!=null&&resultJson.length()>0){
                            if (resultJson.optJSONObject(0).has("AllowAffirm")){
                                try {
                                    AllowAffirm=resultJson.optJSONObject(0).getString("AllowAffirm");
                                    if (AllowAffirm.equals("N")) {
                                        findViewById(R.id.btn_saveData).setVisibility(GONE);
                                        findViewById(R.id.btn_returnData).setVisibility(GONE);
                                    } else{

                                        findViewById(R.id.btn_saveData).setVisibility(View.VISIBLE);
                                        findViewById(R.id.btn_returnData).setVisibility(View.VISIBLE);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            AlertDialog alertDialog = new AlertDialog.Builder(procList.getContext()).
                                    setTitle(getString(R.string.SystemHint)).
                                    setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }).create();
                            if (resultJson.optJSONObject(0).has("ResultInfo")) {
                                try {
                                    alertDialog.setMessage(resultJson.optJSONObject(0).getString("ResultInfo"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } else alertDialog.setMessage("保存成功！");
                            alertDialog.show(); // 显示对话框
                        }
                        break;
                    case MSG_ERRMSG:
                        Bundle bundle=msg.getData();
                        curToast.setText(bundle.getString("MSG"));
                        curToast.show();
                        break;
                    default:
                        break;
                }
            }
        }
    };


    //员工状态表格适配器;
    public final class ProcListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ProcListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return procJSONArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return procJSONArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View  conView = inflater.inflate(R.layout.activity_affirmedit_item, null, false);
            int pullVatListWidth=parent.getWidth();
            int pullVatListHeight=parent.getHeight();
            conView.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,(pullVatListHeight/15)));
            int textColor=getResources().getColor(R.color.text_black);
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (procJSONArray.optJSONObject(position).has("ConColor")){
                    textColor=GetColorValue(procJSONArray.optJSONObject(position).getString("ConColor"));
                }

                TextView tv = (TextView) conView.findViewById(R.id.text_view_WorkNo);// 显示文字
                if (procJSONArray.optJSONObject(position).has("WorkNo"))
                    tv.setText(procJSONArray.optJSONObject(position).get("WorkNo").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.text_view_WorkName);// 显示文字
                if (procJSONArray.optJSONObject(position).has("WorkName"))
                    tv.setText(procJSONArray.optJSONObject(position).get("WorkName").toString());
                tv.setTextColor(Color.BLUE);
                tv = (TextView) conView.findViewById(R.id.text_view_SAMValue);// 显示文字
                tv.setTextColor(textColor);
                if (procJSONArray.optJSONObject(position).has("SAMValue"))
                    tv.setText(String.format("%.3f", procJSONArray.optJSONObject(position).get("SAMValue")));
                tv = (TextView) conView.findViewById(R.id.text_view_TargetValue);// 显示文字
                tv.setTextColor(textColor);
                if (procJSONArray.optJSONObject(position).has("TargetValue"))
                    tv.setText(String.format("%.3f", procJSONArray.optJSONObject(position).get("TargetValue")));
                tv = (TextView) conView.findViewById(R.id.text_view_RptValue);// 显示文字
                tv.setTextColor(textColor);
                if (procJSONArray.optJSONObject(position).has("RptValue"))
                    tv.setText(String.format("%.3f", procJSONArray.optJSONObject(position).get("RptValue")));
                if ((procJSONArray.optJSONObject(position).has("RptValue"))&&(procJSONArray.optJSONObject(position).has("TargetValue"))){
                    if (!procJSONArray.optJSONObject(position).getString("RptValue").equals(procJSONArray.optJSONObject(position).getString("TargetValue")))
                        tv.setBackgroundColor(getResources().getColor(R.color.greenyellow));
                }

                if (procJSONArray.optJSONObject(position).has("NotNormal")) {
                    ImageView img = (ImageView) conView.findViewById(R.id.img_NotNormal);// 显示文字
                    if (procJSONArray.optJSONObject(position).getString("NotNormal").equals("Y")){
                        img.setImageDrawable(getResources().getDrawable(R.mipmap.checkbox_button));
                    } else{
                        img.setImageDrawable(getResources().getDrawable(R.mipmap.checkbox_button_no));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg","OrderGridAdapter_position:"+position);
            return conView;
        }
    }

    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

}
